<template>
  <el-dialog
    v-model="visible"
    title="证书生成"
    :close-on-click-modal="false"
    style="width: 40%;"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="120px"
      @onclick="onSubmit()"
    >
      <el-form-item
        label="证书模板"
        prop="teacherName"
      >
        <el-autocomplete
          v-model="dataForm.name"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
          style="width: 90%;"
        />
      </el-form-item>
      <el-form-item
        label="活动名称"
        prop="teacherName"
      >
        <el-autocomplete
          v-model="dataForm.title"
          :fetch-suggestions="queryActivityAsync"
          placeholder="请输入内容"
          @select="activitySelect"
          style="width: 90%;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ElMessage, ElMessageBox} from 'element-plus'
import {Debounce} from '@/utils/debounce'

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataForm = reactive({
  id: 0,
  templateId: 0,
  relatedId: 0,
  relatedTable: 1,
  status: 0,
  parentId: 0
})
const isSubmit = ref(false)
const dataFormRef = ref(null)
// 表单提交
const onSubmit = Debounce(() => {
  ElMessageBox.confirm('确定进行生成操作?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      dataFormRef.value?.validate((valid) => {
        if (valid) {
          if (isSubmit.value) {
            return
          }
          isSubmit.value = true
          http({
            url: http.adornUrl('/admin/user/certificate/add'),
            method: 'post',
            data: http.adornData({
              templateId: dataForm.templateId,
              relatedId: dataForm.relatedId,
              relatedTable: 1
            })
          })
            .then(() => {
              ElMessage({
                message: '操作成功',
                type: 'success',
                duration: 1000,
                onClose: () => {
                  isSubmit.value = false
                  visible.value = false
                  emit('refreshDataList')
                }
              })
            })
        }
      })
    })
})

const init = () => {
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  getTemplateList()
  getActivityList()
  visible.value = true
}
defineExpose({init})


/**
 * input的搜索
 */
const inputData = reactive({
  restaurants: [],
  state: '',
  timeoutFun: null
})
const querySearchAsync = (queryString, cb) => {
  const restaurants = inputData.restaurants
  const results = queryString ? restaurants.filter(createStateFilter(queryString)) : restaurants
  clearTimeout(inputData.timeoutFun)
  inputData.timeoutFun = setTimeout(() => {
    cb(results)
  }, 3000 * Math.random())
}
const createStateFilter = (queryString) => {
  return (state) => {
    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
  }
}

const getTemplateList = () => {
  http({
    url: http.adornUrl('/admin/certificate/template/list'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({data}) => {
      const list = []
      for (let i = 0; i < data.length; i++) {
        const obj = {
          value: data[i].name,
          templateId: data[i].id
        }
        list.push(obj)
      }
      inputData.restaurants = list
    })
}
const handleSelect = (item) => {
  dataForm.templateId = item.templateId
}
/**
 * activity的搜索
 */
const activityData = reactive({
  restaurants: [],
  state: '',
  timeoutFun: null
})
const queryActivityAsync = (queryString, cb) => {
  const restaurants = activityData.restaurants
  const results = queryString ? restaurants.filter(createActivityFilter(queryString)) : restaurants
  clearTimeout(activityData.timeoutFun)
  activityData.timeoutFun = setTimeout(() => {
    cb(results)
  }, 3000 * Math.random())
}
const createActivityFilter = (queryString) => {
  return (state) => {
    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
  }
}

const getActivityList = () => {
  http({
    url: http.adornUrl('/admin/activity/over'),
    method: 'get',
    params: http.adornParams({roleId: 1})
  })
    .then(({data}) => {
      const list = []
      for (let i = 0; i < data.length; i++) {
        const obj = {
          value: data[i].title,
          relatedId: data[i].id
        }
        list.push(obj)
      }
      activityData.restaurants = list
    })
}
const activitySelect = (item) => {
  dataForm.relatedId = item.relatedId
}
</script>
